package system

import (
	"MoSkeleton/framework/core/dto/response"
	"MoSkeleton/framework/utils"
	system2 "MoSkeleton/models/system"
	"MoSkeleton/services/base"
	s1 "MoSkeleton/web/pogos/request/system"
	"MoSkeleton/web/pogos/response/system"
	"gorm.io/gorm"
)

type SysNoticeService struct {
	base.BaseService
}

func (n *SysNoticeService) GetNoticePage(noticeReq *s1.SysNoticePageReq) (*response.PageResult, error) {
	db := n.getNoticeListVo(nil)
	if noticeReq.NoticeTitle != "" {
		db.Where("notice_title like ?", "%"+noticeReq.NoticeTitle+"%")
	}
	if noticeReq.NoticeType != "" {
		db.Where("notice_type = ?", noticeReq.NoticeType)
	}
	if noticeReq.CreatedBy != "" {
		db.Where("created_by like concat('%', ?, '%') ", noticeReq.CreatedBy)
	}
	rows := make([]*system.SysNoticeItemResp, 0)
	var total int64
	if err := db.Count(&total).Offset(noticeReq.Offset()).Limit(noticeReq.Limit()).Find(&rows).Error; err != nil {
		return nil, err
	}
	pageResult := response.NewFromPageInfoAndData(&noticeReq.PageInfo, &rows, total)
	return pageResult, nil
}

func (n *SysNoticeService) GetNoticeById(id string) (*system.SysNoticeDetailItemResp, error) {
	var notice system.SysNoticeDetailItemResp
	if err := n.getNoticeDetailVo(nil).Where("id = ?", id).First(&notice).Error; err != nil {
		return nil, err
	}
	return &notice, nil
}

func (n *SysNoticeService) AddNotice(noticeReq *s1.SysNoticeAddReq) (bool, error) {
	sysNotice := system2.SysNotice{}

	if err := utils.CopyStruct(&sysNotice, noticeReq); err != nil {
		return false, err
	}
	result := n.GetDb(nil).Create(&sysNotice)
	return result.RowsAffected > 0, result.Error
}

func (n *SysNoticeService) UpdateNotice(noticeReq *s1.SysNoticeUpdateReq) (bool, error) {
	sysNotice := system2.SysNotice{}

	if err := utils.CopyStruct(&sysNotice, noticeReq); err != nil {
		return false, err
	}
	return n.BaseService.UpdateById(n.GetDb(nil), &sysNotice)
}

func (n *SysNoticeService) DeleteNotices(idStrs *[]string) (bool, error) {
	return n.BaseService.DeleteByIds(n.GetDb(nil), &system2.SysNotice{}, idStrs)
}

/*
	   select id, notice_title, notice_type, cast(notice_content as char) as notice_content, status, created_by, created_at, updated_by, updated_at, remark
			from sys_notice
*/
func (n *SysNoticeService) getNoticeListVo(tx *gorm.DB) *gorm.DB {
	selectFields := "id, notice_title, notice_type,  status, created_by, created_at, updated_by, updated_at"
	return n.GetDb(tx).Table("sys_notice").Select(selectFields)
}

func (n *SysNoticeService) getNoticeDetailVo(tx *gorm.DB) *gorm.DB {
	selectFields := "id, notice_title, notice_type, cast(notice_content as char) as notice_content, status, created_by, created_at, updated_at, remark"
	return n.GetDb(tx).Table("sys_notice").Select(selectFields)
}
